import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { getVipPackages, purchaseVip } from '../../services/payment';
import useAuthStore from '../../store/auth';
import usePaymentStore from '../../store/payment';

const VipMembership: React.FC = () => {
  const [packages, setPackages] = useState<any[]>([]);
  const [selectedPackage, setSelectedPackage] = useState<string>('');
  const [loading, setLoading] = useState(true);
  const [purchaseLoading, setPurchaseLoading] = useState(false);
  const [error, setError] = useState('');
  
  const navigate = useNavigate();
  const isAuthenticated = useAuthStore(state => state.isAuthenticated);
  const walletBalance = usePaymentStore(state => state.wallet.balance);
  const updateBalance = usePaymentStore(state => state.updateBalance);
  
  useEffect(() => {
    if (!isAuthenticated) {
      navigate('/login');
      return;
    }
    
    fetchVipPackages();
  }, [isAuthenticated]);
  
  const fetchVipPackages = async () => {
    try {
      setLoading(true);
      setError('');
      
      const response = await getVipPackages();
      
      if (response.code === 200) {
        setPackages(response.data.packages || []);
        if (response.data.packages && response.data.packages.length > 0) {
          setSelectedPackage(response.data.packages[0].id);
        }
      } else {
        setError(response.message || '获取VIP套餐失败');
      }
    } catch (err: any) {
      setError(err.message || '获取VIP套餐失败，请稍后再试');
    } finally {
      setLoading(false);
    }
  };
  
  const handlePurchase = async () => {
    if (!selectedPackage) {
      setError('请选择VIP套餐');
      return;
    }
    
    const pkg = packages.find(p => p.id === selectedPackage);
    if (!pkg) {
      setError('所选套餐不存在');
      return;
    }
    
    if (walletBalance < pkg.price) {
      setError('钱包余额不足，请先充值');
      return;
    }
    
    try {
      setPurchaseLoading(true);
      setError('');
      
      // 调用购买VIP API
      const response = await purchaseVip({
        packageId: selectedPackage,
        paymentType: 'wallet'
      });
      
      if (response.code === 200) {
        // 购买成功，更新钱包余额
        updateBalance(response.data.balance);
        
        // 显示成功消息
        alert('VIP开通成功！');
        
        // 跳转到个人中心
        navigate('/profile');
      } else {
        setError(response.message || '购买失败');
      }
    } catch (err: any) {
      setError(err.message || '购买失败，请稍后再试');
    } finally {
      setPurchaseLoading(false);
    }
  };
  
  // 模拟VIP套餐数据
  const mockPackages = [
    {
      id: 'monthly',
      name: '月度VIP',
      price: 9.9,
      originalPrice: 19.9,
      duration: '30天',
      features: ['无限次使用所有功能', '优先客服支持', '每日运势推送']
    },
    {
      id: 'quarterly',
      name: '季度VIP',
      price: 26.9,
      originalPrice: 59.9,
      duration: '90天',
      features: ['无限次使用所有功能', '优先客服支持', '每日运势推送', '专属风水指导']
    },
    {
      id: 'yearly',
      name: '年度VIP',
      price: 88.0,
      originalPrice: 199.9,
      duration: '365天',
      features: ['无限次使用所有功能', '优先客服支持', '每日运势推送', '专属风水指导', '命理大师一对一咨询']
    }
  ];
  
  const displayPackages = packages.length > 0 ? packages : mockPackages;
  
  if (loading) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-gray-50">
        <div className="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-indigo-500"></div>
      </div>
    );
  }
  
  return (
    <div className="min-h-screen bg-gray-50 py-12 px-4 sm:px-6 lg:px-8">
      <div className="max-w-4xl mx-auto">
        <div className="text-center mb-12">
          <h2 className="text-3xl font-bold text-gray-900">VIP会员</h2>
          <p className="mt-2 text-lg text-gray-600">
            开通VIP会员，畅享所有高级功能
          </p>
        </div>
        
        {error && (
          <div className="text-red-500 text-center mb-6">
            {error}
          </div>
        )}
        
        {/* 钱包余额 */}
        <div className="bg-white rounded-lg shadow-sm p-4 mb-8 text-center">
          <span className="text-gray-700">钱包余额：</span>
          <span className="text-xl font-medium text-indigo-600">¥ {walletBalance.toFixed(2)}</span>
          <button
            onClick={() => navigate('/wallet')}
            className="ml-4 inline-flex items-center px-3 py-1 border border-transparent text-sm font-medium rounded-md text-indigo-700 bg-indigo-100 hover:bg-indigo-200 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
          >
            充值
          </button>
        </div>
        
        {/* VIP套餐列表 */}
        <div className="grid grid-cols-1 gap-6 sm:grid-cols-2 lg:grid-cols-3 mb-8">
          {displayPackages.map((pkg) => (
            <div
              key={pkg.id}
              className={`bg-white rounded-lg shadow-sm overflow-hidden transition-shadow duration-300 ${
                selectedPackage === pkg.id ? 'ring-2 ring-indigo-500 shadow-md' : ''
              }`}
              onClick={() => setSelectedPackage(pkg.id)}
            >
              <div className="p-6">
                <div className="flex justify-between items-center mb-4">
                  <h3 className="text-xl font-bold text-gray-900">{pkg.name}</h3>
                  <div className="flex items-center">
                    <input
                      type="radio"
                      checked={selectedPackage === pkg.id}
                      onChange={() => setSelectedPackage(pkg.id)}
                      className="h-4 w-4 text-indigo-600 border-gray-300 focus:ring-indigo-500"
                    />
                  </div>
                </div>
                
                <div className="mb-4">
                  <span className="text-3xl font-bold text-indigo-600">¥{pkg.price}</span>
                  {pkg.originalPrice && (
                    <span className="ml-2 text-sm text-gray-500 line-through">¥{pkg.originalPrice}</span>
                  )}
                  <span className="ml-2 text-gray-500">/ {pkg.duration}</span>
                </div>
                
                <ul className="space-y-2 mb-6">
                  {pkg.features.map((feature, index) => (
                    <li key={index} className="flex items-start">
                      <svg className="h-5 w-5 text-green-500 mr-2" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor">
                        <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clipRule="evenodd" />
                      </svg>
                      <span className="text-gray-700">{feature}</span>
                    </li>
                  ))}
                </ul>
              </div>
            </div>
          ))}
        </div>
        
        {/* 购买按钮 */}
        <div className="text-center">
          <button
            onClick={handlePurchase}
            disabled={purchaseLoading || !selectedPackage}
            className={`inline-flex items-center px-6 py-3 border border-transparent text-base font-medium rounded-md shadow-sm text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 ${
              purchaseLoading || !selectedPackage ? 'opacity-70 cursor-not-allowed' : ''
            }`}
          >
            {purchaseLoading ? '处理中...' : '立即开通'}
          </button>
          
          <p className="mt-4 text-sm text-gray-500">
            开通即表示您同意<a href="#" className="text-indigo-600 hover:text-indigo-500">《VIP会员服务协议》</a>
          </p>
        </div>
        
        {/* VIP特权说明 */}
        <div className="mt-12 bg-white rounded-lg shadow-sm p-6">
          <h3 className="text-xl font-bold text-gray-900 mb-4">VIP特权说明</h3>
          
          <div className="grid grid-cols-1 gap-6 sm:grid-cols-2 lg:grid-cols-3">
            <div className="flex flex-col items-center">
              <div className="bg-indigo-100 rounded-full p-3 mb-3">
                <svg className="h-6 w-6 text-indigo-600" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
                </svg>
              </div>
              <h4 className="text-lg font-medium text-gray-900 mb-1">无限次使用</h4>
              <p className="text-gray-500 text-center">所有功能无限次使用，无需单独付费</p>
            </div>
            
            <div className="flex flex-col items-center">
              <div className="bg-indigo-100 rounded-full p-3 mb-3">
                <svg className="h-6 w-6 text-indigo-600" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 10V3L4 14h7v7l9-11h-7z" />
                </svg>
              </div>
              <h4 className="text-lg font-medium text-gray-900 mb-1">优先服务</h4>
              <p className="text-gray-500 text-center">专属客服通道，问题优先解答</p>
            </div>
            
            <div className="flex flex-col items-center">
              <div className="bg-indigo-100 rounded-full p-3 mb-3">
                <svg className="h-6 w-6 text-indigo-600" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2" />
                </svg>
              </div>
              <h4 className="text-lg font-medium text-gray-900 mb-1">专属内容</h4>
              <p className="text-gray-500 text-center">独家命理内容，每日运势推送</p>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default VipMembership;
